from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from tensorflow.keras import layers, models, losses, metrics, optimizers
# 1. 读取乳腺癌数据集
# 读取数据，切分x, y
data = load_breast_cancer()
x = data.data
y = data.target
print(x.shape)

#分割数据集
# 将数据切分为训练集和测试集
# 使用训练集训练模型，测试集做验证
x_train, x_test, y_train, y_test = train_test_split(x, y)
# 使用二分类模型进行处理，建立模型序列
model = models.Sequential()
model.add(layers.Dense(1, input_dim=(30), activation='sigmoid'))
model.compile(optimizer=optimizers.Adam(1e-2),
              loss=losses.binary_crossentropy, metrics=[metrics.binary_accuracy])
#训练模型：validation_data验证集数据，
#返回的history数据包含: 训练集(loss+metrics)、验证集(loss+metrics), 既要看fit中包含哪些数据集，也要看compile配置中有哪些指标(loss,metrics等)
history = model.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=200)
# 绘制准确率和损失值变化曲线
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']

loss = history.history['loss']  #训练集loss
binary_accuracy = history.history['binary_accuracy']  #训练集的binary_accuracy
val_loss = history.history['val_loss']#验证集loss
val_binary_accuracy = history.history['val_binary_accuracy']#验证集的binary_accuracy
#画出loss曲线
plt.plot(loss, color='red', label='训练损失')
plt.plot(val_loss, color='blue', label='验证损失')
plt.legend()
plt.show()
#画出accuracy曲线
plt.plot(binary_accuracy, color='red', label='训练准确率')
plt.plot(val_binary_accuracy, color='blue', label='验证准确率')
plt.legend()
plt.show()